package org.dromara.netbar.util;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import org.dromara.common.core.constant.NetbarConstants;
import org.dromara.netbar.domain.vo.NetbarCouponVo;

import java.util.Calendar;
import java.util.Date;

/**
 * @author ZhouWenTao
 * @create 2025-08-01 22:15
 */
public class CouponUtils {
    /**
     * 检查券是否有效
     * @param coupon 券对象 {usableTimeStart, usableTimeEnd, validTermType}
     * @param currentTimeMillis 当前时间戳
     * @return 是否有效 true/false
     */
    public static boolean checkCouponBsValid(NetbarCouponVo coupon, long currentTimeMillis){
        if (null == coupon) {
            return false;
        }

        boolean isTimeValid = true;
        if(NetbarConstants.Coupon.TYPE_2.equals(coupon.getCouponType()) || NetbarConstants.Coupon.TYPE_3.equals(coupon.getCouponType())){
            // 包时券、时段券 需要判断使用小时段
            // 获取当前小时
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(currentTimeMillis);
            int currentHour = cal.get(Calendar.HOUR_OF_DAY);

            // 获取券的时段范围
            int startHour = Integer.parseInt(coupon.getUsableTimeStart());
            int endHour = Integer.parseInt(coupon.getUsableTimeEnd());
            // 判断时段是否有效
            if (startHour < endHour) {
                // 包时 (比如 8-12点) - 当前小时在[startHour, endHour)范围内有效
                isTimeValid = currentHour >= startHour && currentHour < endHour;
            } else {
                // 包夜 (比如 22-8点) - 当前小时>=startHour或<endHour时有效
                isTimeValid = currentHour >= startHour || currentHour < endHour;
            }

            if (isTimeValid && NetbarConstants.Coupon.TYPE_2.equals(coupon.getCouponType())) {
                // 卡券使用时间
                Date useTime = coupon.getUseTime();
                if (null != useTime) {
                    // 卡券可以小时数
                    long hourDuration = coupon.getHourDuration();
                    // 需要计算是否已经超时长
                    long duration = DateUtil.between(useTime, new Date(), DateUnit.HOUR);
                    isTimeValid = duration < hourDuration;
                }
            }
        }

        if (2 == coupon.getValidTermType()) {
            if(null == coupon.getValidDateStart() || null == coupon.getValidDateEnd()) return false;
            // 指定日期券 - 还要检查日期范围
            boolean isDateValid = currentTimeMillis >= coupon.getValidDateStart().getTime()
                && currentTimeMillis <= coupon.getValidDateEnd().getTime();
            return isDateValid && isTimeValid;
        }

        // 永久券 - 只检查时段
        return isTimeValid;
    }
}
